<?php
namespace BABA\Omnipay\Components;

use Illuminate\Support\Facades\DB;
use BABA\Omnipay\Models\Settings;
use Omnipay\Omnipay;
use Illuminate\Support\Facades\Event;
use Lang;
use Illuminate\Support\Facades\Log;
use BABA\EBill\Models\EBillOrder as EBillOrderModel;

class Paid extends \Cms\Classes\ComponentBase
{

    public function componentDetails()
    {
        return [
            'name' => Lang::get('baba.omnipay::lang.components.paid.name'),
            'description' => Lang::get('baba.omnipay::lang.components.paid.description'),
        ];
    }

    public function defineProperties()
    {
        return [
            'table' => [
                'title'             => Lang::get('baba.omnipay::lang.components.paid.table.title'),
                'description'       => Lang::get('baba.omnipay::lang.components.paid.table.description'),
                'default'           => 'baba_ebill_order',
                'type'              => 'string',
                'validationPattern' => '^[a-z_]+$',
                'validationMessage' => Lang::get('baba.omnipay::lang.components.paid.table.validation'),
            ],
            'PSP' => [
                'title'             => Lang::get('baba.omnipay::lang.components.paid.PSP.title'),
                'description'       => Lang::get('baba.omnipay::lang.components.paid.PSP.description'),
                'default'           => 'Mollie',
                'type'              => 'dropdown',
                'options'           => [
                    'Mollie'            => 'Mollie',
                    'PayPal_Express'    => 'PayPal_Express'
                ]
            ],
            'ApiKey' => [
                'title'             => Lang::get('baba.omnipay::lang.components.paid.ApiKey.title'),
                'description'       => Lang::get('baba.omnipay::lang.components.paid.ApiKey.description'),
                'type'              => 'string',
                'group'             => 'Mollie'
            ],

            'Username' => [
                'title'             => Lang::get('baba.omnipay::lang.components.paid.Username.title'),
                'description'       => Lang::get('baba.omnipay::lang.components.paid.Username.description'),
                'type'              => 'string',
                'group'             => 'PayPal_Express'
            ],
            'Password' => [
                'title'             => Lang::get('baba.omnipay::lang.components.paid.Password.title'),
                'description'       => Lang::get('baba.omnipay::lang.components.paid.Password.description'),
                'type'              => 'string',
                'group'             => 'PayPal_Express'
            ],
            'Signature' => [
                'title'             => Lang::get('baba.omnipay::lang.components.paid.Signature.title'),
                'description'       => Lang::get('baba.omnipay::lang.components.paid.Signature.description'),
                'type'              => 'string',
                'group'             => 'PayPal_Express'
            ],
            'TestMode' => [
                'title'             => Lang::get('baba.omnipay::lang.components.paid.TestMode.title'),
                'description'       => Lang::get('baba.omnipay::lang.components.paid.TestMode.description'),
                'default'           => false,
                'type'              => 'checkbox',
                'group'             => 'PayPal_Express'
            ]
        ];
    }

    function onRun()//onRender
    {
        // get order from the DB based on ID
        $id = isset($_GET['id']) ? $_GET['id'] : false;
        $token = isset($_GET['token']) ? $_GET['token'] : false;
        $payerID = isset($_GET['payerID']) ? $_GET['payerID'] : false;
        if(is_numeric($id))
        {
            $order = Db::table( $this->property('table') ) // e.g. briddle_book_payment
            ->select(
                Settings::get('map_paymentid','paymentid'),
                Settings::get('map_amount','amount'),
                Settings::get('map_currency','currency'),
                Settings::get('map_id','id')
            )
            ->where(Settings::get('map_id','id'),$id)
            ->first();
        }else{
            Log::error('order id is null!!',$payerID,$token);
        }

        if(isset($order) && $order)
        {
            // Setup PSP
            $gateway = Omnipay::create( $this->property('PSP') );// e.g. Mollie

            switch($this->property('PSP'))
            {
                case "Mollie":
                    $gateway->setApiKey( $this->property('ApiKey') ); // e.g. test_12345 as used by Mollie

                    $response = $gateway->completePurchase(array(
                        'transactionReference' => $order->paymentid,
                    ))->send();
                break;
                case "PayPal_Express":
                    $gateway->setUsername( $this->property('Username') );
                    $gateway->setPassword( $this->property('Password') );
                    $gateway->setSignature( $this->property('Signature') );
                    $gateway->setTestMode( $this->property('TestMode') );// e.g. true

                    //https://www.briddle.net/demo/en/?id=1&token=EC-8JC19612GL0546248&PayerID=AKJ5YX36ZBFLQ
                    $response = $gateway->completePurchase(array(
                        'transactionReference' =>  $payerID, // $order->paymentid,//$payerID , 如果不对，则下面的isSuccessful会返回false
                        'transactionId' => $token,
                        'amount' => $order->amount,
                        'currency' => $order->currency
                    ))->send();
                break;
            }

            if ($response->isSuccessful())
            {
                // mark as paid
                // $order = Db::table( $this->property('table') )
                // ->where(
                //     Settings::get('map_id', 'id'), $id
                // );
                // Settings::get('map_paid', 'ispaid')
                $order = EBillOrderModel::find($id);

                if($order->ispaid!=1){
                    Event::fire('baba.omnipay.paid',$order);
                }


                $order->ispaid = 1;
                $order->paied_at=now();
                $order->save();

                $this->page['ispaid'] = 'yes';
            }
            else
            {
                //die($response->getMessage());

                // NOT paid
                $this->page['errmsg']  = $response->getMessage();
                $this->page['ispaid'] = 'no';
            }
        }else{
            Log::error('order is null!!',[$id,$payerID,$token]);
        }
    }
}
